package com.boyuan.huijiaoyu;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.example.contactfragment.ContactService;
import com.example.contactfragment.HomeContactOrgActivity;
import com.example.nearby.NearbyPeople;
import com.example.newfragment.DetailPerson;
import com.google.gson.Gson;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.MapService;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.nostra13.universalimageloader.core.ImageLoader;

public class PeopleNearActivity extends BaseActivity implements LocationSource,
		AMapLocationListener, OnClickListener {

	private MapView mapView;
	private AMap aMap;
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager;

	private ImageView mImg_poipeople_eye;
	private ImageView img_drawer_raindrops;
	private UiSettings mUiSettings;
	private TextView mTv_online_num;
	private RelativeLayout mRela_poipeople_eye;
	private ListView mListView;
	private boolean isLightEye = false;
	private boolean isRainDrops = false;

	private Animation slidein;
	private Animation slideout;
	private PoiPeopleAdapter poiPeopleAdapter;
	private MapService mapService;
	private List<NearbyPeople> nearbyPeoples = new ArrayList<NearbyPeople>();
	private String tag = "PeopleNearActivity";
	private ImageLoader imageLoader;
	private ContactService contactService;
	private DetailPerson homeContactDetailEntity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 不显示程序的标题栏
		setContentView(R.layout.activity_people_near);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		init();

	}

	private void init() {
		imageLoader = ImageLoader.getInstance();

		findViewById(R.id.ima_poipeople_back).setOnClickListener(this);
		findViewById(R.id.tv_back_txt).setOnClickListener(this);
		mImg_poipeople_eye = (ImageView) findViewById(R.id.img_poipeople_eye);
		mRela_poipeople_eye = (RelativeLayout) findViewById(R.id.rela_poipeople_eye);
		img_drawer_raindrops = (ImageView) findViewById(R.id.img_drawer_raindrops);
		mRela_poipeople_eye.setOnClickListener(this);
		img_drawer_raindrops.setOnClickListener(this);
		mListView = (ListView) findViewById(R.id.listView1);
		mTv_online_num = (TextView) findViewById(R.id.tv_online_num);

		poiPeopleAdapter = new PoiPeopleAdapter();
		mListView.setAdapter(poiPeopleAdapter);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long arg3) {
				NearbyPeople nearbyPeople = nearbyPeoples.get(position);
				String accountId = nearbyPeople.getAccountId();
				if (accountId != null) {
					getContactDetail(accountId);
				} else {
					ToastHelper.showMsg(PeopleNearActivity.this, "获取联系人详情失败",
							false);
				}
			}
		});

		slidein = AnimationUtils.loadAnimation(this,
				R.anim.poipeople_drawer_raindrops_slidein);
		slideout = AnimationUtils.loadAnimation(this,
				R.anim.poipeople_drawer_raindrops_slideout);

		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}
	}

	private void setUpMap() {
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
		// aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
		// aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
		// aMap.setInfoWindowAdapter(this);

		mUiSettings = aMap.getUiSettings();
		mUiSettings.setZoomGesturesEnabled(true);
		mUiSettings.setScrollGesturesEnabled(true);// 设置是否可以拖拽
		mUiSettings.setZoomControlsEnabled(true);// 设置点击放大缩小按钮是否显示
		mUiSettings.setScaleControlsEnabled(true);// 设置点击放大缩小按钮是否显示
	}

	class ViewHolder {
		ImageView img_poipeople_headicon;
		TextView Tv_poipeople_name;
		TextView Tv_poipeople_distance;
		ImageView img_poipeople_sex;
		TextView Tv_poipeople_job;
	}

	class PoiPeopleAdapter extends BaseAdapter {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;

			View view = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				view = getLayoutInflater().inflate(
						R.layout.poipeople_list_item, null);
				viewHolder.img_poipeople_headicon = (ImageView) view
						.findViewById(R.id.img_poipeople_headicon);
				viewHolder.img_poipeople_sex = (ImageView) view
						.findViewById(R.id.img_poipeople_sex);
				viewHolder.Tv_poipeople_name = (TextView) view
						.findViewById(R.id.Tv_poipeople_name);
				viewHolder.Tv_poipeople_distance = (TextView) view
						.findViewById(R.id.Tv_poipeople_distance);
				viewHolder.Tv_poipeople_job = (TextView) view
						.findViewById(R.id.Tv_poipeople_job);
				view.setTag(viewHolder);

			} else {
				view = convertView;
				viewHolder = (ViewHolder) view.getTag();
			}
			NearbyPeople nearbyPeople = nearbyPeoples.get(position);

			viewHolder.Tv_poipeople_name.setText(nearbyPeople.getRealname());
			viewHolder.Tv_poipeople_distance.setText(nearbyPeople.getDistance()
					+ "米");
			viewHolder.Tv_poipeople_job.setText(nearbyPeople.getJobName());
			if ("男".equals(nearbyPeople.getSex())) {
				viewHolder.img_poipeople_sex
						.setImageResource(R.drawable.contact_male);
			} else {
				viewHolder.img_poipeople_sex
						.setImageResource(R.drawable.contact_female);
			}
			// String uri = "http://42.62.50.218:5757/avatar?uid="
			// + nearbyPeople.getMobile();
			// imageLoader.displayImage(uri, viewHolder.img_poipeople_headicon);
			return view;
		}

		@Override
		public int getCount() {
			return nearbyPeoples.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用destroy()方法
			// 其中如果间隔时间为-1，则定位只定一次
			// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
			mAMapLocationManager.requestLocationData(
					LocationProviderProxy.AMapNetwork, -1, 10, this);
		}
	}

	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destroy();
		}
		mAMapLocationManager = null;
	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (mListener != null && amapLocation != null) {
			if (amapLocation != null
					&& amapLocation.getAMapException().getErrorCode() == 0) {
				mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
				double lat = amapLocation.getLatitude();
				double lng = amapLocation.getLongitude();
				getPoiPeople(lat, lng);

			} else {
				Log.e("AmapErr", "Location ERR:"
						+ amapLocation.getAMapException().getErrorCode());
			}
		}
	}

	private void getPoiPeople(double lat, double lng) {
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		String uid = sp.getString("id", "");
		if (mapService == null) {
			mapService = new MapService(this);
		}
		Log.e(tag, "uid = " + uid);
		mapService.getNearByPeopleService(uid, lat, lng,
				new GetOneRecordListener<List<NearbyPeople>>() {

					@Override
					public void onFinish(List<NearbyPeople> data) {
						Log.e(tag, "data.size = " + data.size());
						nearbyPeoples.clear();
						if (data != null) {
							nearbyPeoples.addAll(data);
						}
						addMarkersToMap();
						poiPeopleAdapter.notifyDataSetChanged();
						mTv_online_num.setText("在线人数:" + nearbyPeoples.size());
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(PeopleNearActivity.this, Message,
								false);
					}
				});
	}

	private void addMarkersToMap() {
		Gson gson = new Gson();
		for (int i = 0; i < nearbyPeoples.size(); i++) {
			NearbyPeople nearbyPeople = nearbyPeoples.get(i);
			String lat = nearbyPeople.getLat();
			String lng = nearbyPeople.getLng();
			String realname = nearbyPeople.getRealname();
			String sex = nearbyPeople.getSex();
			LatLng latLng = new LatLng(Double.valueOf(lat), Double.valueOf(lng));
			MarkerOptions markerOption = new MarkerOptions();
			markerOption.position(latLng);
			markerOption.title(realname);
			markerOption.snippet(gson.toJson(nearbyPeople));
			markerOption.draggable(false);
			markerOption.icon(BitmapDescriptorFactory
					.fromView(getMapPaoPaoView(realname, sex)));
			aMap.addMarker(markerOption);
		}
	}

	public View getMapPaoPaoView(String Realname, String sex) {
		View view = LayoutInflater.from(PeopleNearActivity.this).inflate(
				R.layout.poipeople_light_dark_view, null);
		LinearLayout lin_poipeople_showname = (LinearLayout) view
				.findViewById(R.id.lin_poipeople_showname);
		ImageView img_poipeople_sex = (ImageView) view
				.findViewById(R.id.img_poipeople_sex);
		TextView Tv_poipeople_name = (TextView) view
				.findViewById(R.id.Tv_poipeople_name);
		Tv_poipeople_name.setText(Realname);

		if ("男".equals(sex)) {
			img_poipeople_sex.setImageResource(R.drawable.poipeople_man);
		} else {
			img_poipeople_sex.setImageResource(R.drawable.poipeople_woman);
		}

		if (isLightEye) {
			lin_poipeople_showname.setVisibility(View.VISIBLE);
		} else {
			lin_poipeople_showname.setVisibility(View.INVISIBLE);
		}

		return view;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_back_txt:
			finish();
			break;
		case R.id.ima_poipeople_back:
			finish();
			break;
		case R.id.rela_poipeople_eye:
			img_eye();
			break;
		case R.id.img_drawer_raindrops:
			img_drawer_raindrops();
			break;

		default:
			break;
		}
	}

	private void img_drawer_raindrops() {
		isRainDrops = !isRainDrops;
		if (isRainDrops) {
			img_drawer_raindrops.setImageResource(R.drawable.raindrops);
			mapView.setVisibility(View.GONE);
			mapView.startAnimation(slideout);
			mListView.setVisibility(View.VISIBLE);
			mListView.startAnimation(slidein);
			mTv_online_num.setVisibility(View.GONE);
		} else {
			img_drawer_raindrops.setImageResource(R.drawable.drawer);
			mListView.setVisibility(View.GONE);
			mListView.startAnimation(slideout);
			mapView.setVisibility(View.VISIBLE);
			mapView.startAnimation(slidein);
			mTv_online_num.setVisibility(View.VISIBLE);
		}
	}

	private void img_eye() {
		isLightEye = !isLightEye;
		if (isLightEye) {
			mImg_poipeople_eye.setImageResource(R.drawable.poipeople_light);
			aMap.clear();
			addMarkersToMap();
			if (isRainDrops) {
				mListView.setVisibility(View.GONE);
				mListView.startAnimation(slideout);
				mapView.setVisibility(View.VISIBLE);
				mapView.startAnimation(slidein);
				mTv_online_num.setVisibility(View.VISIBLE);
				isRainDrops = !isRainDrops;
				img_drawer_raindrops.setImageResource(R.drawable.drawer);
			}
		} else {
			mImg_poipeople_eye.setImageResource(R.drawable.poipeople_dark);
			aMap.clear();
			addMarkersToMap();
			if (isRainDrops) {
				mListView.setVisibility(View.GONE);
				mListView.startAnimation(slideout);
				mapView.setVisibility(View.VISIBLE);
				mapView.startAnimation(slidein);
				mTv_online_num.setVisibility(View.VISIBLE);
				isRainDrops = !isRainDrops;
				img_drawer_raindrops.setImageResource(R.drawable.drawer);
			}
		}
	}

	private void getContactDetail(final String contactId) {

		if (contactService == null) {
			contactService = new ContactService(getApplicationContext());
		}

		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		final String yonghuID = sp.getString("id", "");

		showLoading(getString(R.string.loading_data));

		contactService.getContactdetail(yonghuID, contactId,
				new GetOneRecordListener<DetailPerson>() {

					@Override
					public void onFinish(DetailPerson data) {
						// TODO Auto-generated method stub
						hideLoading();
						homeContactDetailEntity = data;
						if (homeContactDetailEntity.getIs_common().equals("1")
								|| homeContactDetailEntity.getIs_favorite()
										.equals("1")) {
							Intent intent = new Intent(PeopleNearActivity.this,
									HomeContactDeail2Activity.class);
							intent.putExtra("uid",
									homeContactDetailEntity.getUid());
							startActivity(intent);
							finish();
						} else {
							Intent intent = new Intent(PeopleNearActivity.this,
									HomeContactDeail1Activity.class);
							intent.putExtra("realname",
									homeContactDetailEntity.getRealname());
							intent.putExtra("sex",
									homeContactDetailEntity.getSex());
							intent.putExtra("account_mobile",
									homeContactDetailEntity.getAccount_mobile());
							intent.putExtra("mobile",
									homeContactDetailEntity.getMobile());
							intent.putExtra("yonghuID", yonghuID);
							intent.putExtra("uid", contactId);
							startActivity(intent);
							finish();
						}

					}

					@Override
					public void onFailed(String Message) {
						hideLoading();
						ToastHelper.showMsg(PeopleNearActivity.this, Message,
								false);
					}
				});
	}

	@Override
	public void backClicked() {
		if (isShowingLoading()) {
			hideLoading();
		} else {
			setResult(RESULT_OK);
			isBackAllowed = true;
		}
	}

}
